package cn.hj.domain.strategy.service.rule.chain.impl;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.hj.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.hj.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 黑名单责仁链
 */
@Component("rule_blacklist")
@Slf4j
public class BlackListLogicChain extends AbstractLogicChain {


    @Resource
    private IStrategyRepository strategyRepository;
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(Long strategyId, String userId) {
        log.info("抽奖责任链-黑名单开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModels());
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModels());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.parseInt(splitRuleValue[0]);
        // 黑名单抽奖判断
        String[] userBlackIds = splitRuleValue[1].split(Constants.SPLIT);
        for (String userBlackId : userBlackIds) {
            if (userId.equals(userBlackId)) {
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModels(), awardId);
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModels())
                        .build();
            }
        }

        // 过滤其他责任链
        log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModels());
        return next().logic(strategyId, userId);
    }

    @Override
    protected String ruleModels() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }
}
